//
//  RequestManager.swift
//  SwiftDemo
//
//  Created by tenltrs on 2018/8/28.
//  Copyright © 2018年 Tenltrs. All rights reserved.
//


import UIKit

@objcMembers class AjaxResult: NSObject {
    
    var code : String?
    
    var message : String?
    
    var data : Any?
    
    var success : Bool = false
}

typealias ResultBlock = (_ result : AjaxResult)->()
typealias Failure = (_ error : Error)->()
typealias ProgressBlock = (_ progress : Progress)->()

class RequestManager: NSObject {
    
    static var updateSessionManager : SessionManager?
    
    /// 普通请求
    ///
    /// - Parameters:
    ///   - url: 请求地址
    ///   - parameter: 请求参数
    ///   - isLoad: 是否加载提示
    ///   - success: 成功返回
    ///   - failure: 失败返回
    static func POST(url : String, parameter : Parameters?, target : Any, isLoad : Bool,success : ResultBlock?,failure : Failure?){
        
        logger.info("url ==== \(url)")
        logger.info("par ===== \(parameter ?? [:])")
    
        if isLoad {
            HUDManager.loadShowing()
        }
    
        let baseVC = target as! UIViewController
        
        //设置请求配置
        let configuration = URLSessionConfiguration.default
        configuration.timeoutIntervalForRequest = 30  //设置超时时间
        if (baseVC.sessionManager==nil) {
            baseVC.sessionManager = Alamofire.SessionManager(configuration: configuration)
        }
        
        baseVC.sessionManager!.request(url, method: .post, parameters: parameter, headers: getHeader()).response(completionHandler: { (response) in
            HUDManager.loadHideing()
            if response.error == nil{
                let result : AjaxResult = self.generateAjaxResult(respons: response.data!)
                if success != nil{
                    success!(result)
                }
                //请求成功
            }else{
                //请求失败
                logger.error(response.error!)
                if failure != nil{
                    failure!(response.error!)
                }
            }
        })
    }
    
    
    /// 普通请求
    ///
    /// - Parameters:
    ///   - url: 请求地址
    ///   - parameter: 请求参数
    ///   - isLoad: 是否加载提示
    ///   - success: 成功返回
    ///   - failure: 失败返回
    static func GET(url : String, parameter : Parameters?, target : Any, isLoad : Bool,success : ResultBlock?,failure : Failure?){
        
        logger.info("url ==== \(url)")
        logger.info("par ===== \(parameter ?? [:])")
        
        if isLoad {
            HUDManager.loadShowing()
        }
        
        let baseVC = target as! UIViewController
        
        //设置请求配置
        let configuration = URLSessionConfiguration.default
        configuration.timeoutIntervalForRequest = 30  //设置超时时间
        if (baseVC.sessionManager==nil) {
            baseVC.sessionManager = Alamofire.SessionManager(configuration: configuration)
        }
        
        baseVC.sessionManager!.request(url, method: .get, parameters: parameter, headers: getHeader()).response(completionHandler: { (response) in
            HUDManager.loadHideing()
            if response.error == nil{
                let result : AjaxResult = self.generateAjaxResult(respons: response.data!)
                if success != nil{
                    success!(result)
                }
                //请求成功
            }else{
                //请求失败
                logger.error(response.error!)
                if failure != nil{
                    failure!(response.error!)
                }
            }
        })
    }
    
    /// json格式 请求
    ///
    /// - Parameters:
    ///   - url: 请求地址
    ///   - parameter: 参数
    ///   - isLoad: 是否显示弹窗
    ///   - success: 成功返回
    ///   - failure: 失败返回
    static func POSTWithJSON(url : String, parameter : Parameters?, target : Any, isLoad : Bool,success : ResultBlock?,failure : Failure?){
        
        logger.info("url ==== \(url)")
        logger.info("par ===== \(parameter ?? [:])")
        
        if isLoad {
            HUDManager.loadShowing()
        }
        
        let baseVC = target as! UIViewController //获取当前请求控制器
        //设置请求配置
        let configuration = URLSessionConfiguration.default
        configuration.timeoutIntervalForRequest = 30  //设置超时时间
        
        if (baseVC.sessionManager==nil) {
            baseVC.sessionManager = Alamofire.SessionManager(configuration: configuration)
        }
        
        baseVC.sessionManager!.request(url, method: .post, parameters: parameter, encoding: JSONEncoding.default, headers: getHeader()).response(completionHandler: { (response) in
            HUDManager.loadHideing()
            if response.error == nil{
                let result : AjaxResult = self.generateAjaxResult(respons: response.data!)
                if success != nil{
                    success!(result)
                }
                //请求成功
            }else{
                //请求失败
                logger.error(response.error!)
                if failure != nil{
                    failure!(response.error!)
                }
            }
        })
    }
    
    
    /// 文件上传
    ///
    /// - Parameters:
    ///   - url: 请求地址
    ///   - parameter: 参数
    ///   - fileData: 文件参数  key格式： 文件名字/参数名称.文件后缀   value: 文件二进制
    ///   - progress: 进度回调
    ///   - success: 成功回调
    ///   - failure: 失败回调
    static func POSTWithUpdate(url : String, parameter : [String:String]?, target : Any,fileData : [String:Data],progress : ProgressBlock? ,success : ResultBlock?,failure : Failure?){
        
        logger.info("url ==== \(url)")
        logger.info("par ===== \(parameter ?? [:])")

        //设置请求配置
        let configuration = URLSessionConfiguration.default
        configuration.timeoutIntervalForRequest = 30  //设置超时时间
        
        let baseVC = target as! UIViewController //获取当前请求控制器
        
        if (baseVC.sessionManager==nil) {
            baseVC.sessionManager = Alamofire.SessionManager(configuration: configuration)
        }
        baseVC.sessionManager!.upload(multipartFormData: { (formData) in
            
            for (key, value) in fileData{
                let name : String = key.components(separatedBy: ".").first!
                let fileName : String = name.components(separatedBy: "/").first!
                let parName : String = name.components(separatedBy: "/").last!
                let type : String = key.components(separatedBy: ".").last!
                formData.append(value, withName: parName, fileName: fileName, mimeType: type)
            }
            
            if parameter != nil{
                for (key,value) in parameter!{
                    formData.append(value.data(using: String.Encoding.utf8)!, withName: key)
                }
            }
            
        }, to: url, method: .post,encodingCompletion: { (encodingResult) in
            
            switch encodingResult{
            case .success(let uploadFile, _, _):
                //上传进度回调
                uploadFile.uploadProgress(closure: { (pro) in
                    logger.info("上传进度=======\(pro.fractionCompleted)")
                    if progress != nil{
                        progress!(pro)
                    }
                })
                //上传结果回调
                uploadFile.response(completionHandler: { (response) in
                    if response.error == nil{
                        let result : AjaxResult = self.generateAjaxResult(respons: response.data!)
                        if success != nil{
                            success!(result)
                        }
                        //请求成功
                    }else{
                        //请求失败
                        logger.error(response.error!)
                        if failure != nil{
                            failure!(response.error!)
                        }
                    }
                })
                break
            case .failure( let error):
                logger.error(error)
                break
            }
        })

    }
    
    /// 解析请求结果返回模型
    ///
    /// - Parameter respons: 返回请求结果
    /// - Returns: 返回请求模型
    static func generateAjaxResult(respons : Any)->AjaxResult{
        
        if respons is Data {
            var result : AjaxResult?
            let block : SBJson5ValueBlock = {(v, stop) in
                result = AjaxResult.mj_object(withKeyValues: v!)
            }
            
            let errorBlock : SBJson5ErrorBlock = {(error) in
                
                print("json解析失败\n err: \(String(describing: error))")
            }
            
            let parser : SBJson5Parser = SBJson5Parser.multiRootParser(block, errorHandler: errorBlock) as! SBJson5Parser
            
            parser.parse((respons as! Data))
            
            if result?.code=="200"{
                 result?.success=true
            }
            
            return result!
        }else{
            let result : AjaxResult = AjaxResult.init()
            result.mj_setKeyValues(respons as! [String : Any])
            if result.code=="200"{
                result.success=true
            }
            return result
        }
        
    }
    
    /// 设置请求头 没有可返回nil
    ///
    /// - Returns: 返回请求头
    private static func getHeader() -> [String:String]? {
        
        var headers : Dictionary = Dictionary<String, String>()
        headers["Package-Id"] = "com.kuaikan.comic"
        headers["Lower-Flow"] = "No"
        headers["Connection"] = "keep-alive"
        headers["User-Agent"] = "Kuaikan/5.13.5/513005(iPhone;iOS 12.0.1;Scale/2.00;WiFi;1334*750)"
        headers["Muid"] = "db8e2b59b563916337c49e379e9d9849"
        headers["Accept-Encoding"] = "br, gzip, deflate"
        headers["Accept-Language"] = "zh-Hans-CN;q=1, en-CN;q=0.9"
        headers["HW-Model"] = "iPhone8,1"
        headers["X-Device"] = "I:09F84010-B0DB-4FAF-AE3E-B46119A3D04B"
        return headers
    }
    
}
